package org.lds.message.center.core;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.lds.message.center.common.MessageService;
import org.lds.message.center.common.util.AssertUtil;
import org.lds.message.center.core.enums.CoreErrorEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class MessageServiceFinder implements ApplicationContextAware, InitializingBean {
    private ApplicationContext context;

    private Map<String, MessageService> finder = new HashMap<>();

    /**
     * channel = channelType:channelName
     * @param channel
     */
    public MessageService find(String channel) {
        AssertUtil.assertTrue(Objects.nonNull(channel), CoreErrorEnum.CHANNEL_INVALID);
        MessageService messageService = finder.get(channel);
        AssertUtil.assertTrue(Objects.nonNull(messageService), CoreErrorEnum.CHANNEL_INVALID);
        return messageService;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, MessageService> ossServiceMap = context.getBeansOfType(MessageService.class);
        if (MapUtils.isEmpty(ossServiceMap)) {
            log.warn("消息中心服务没有发现提供者");
        } else {
            ossServiceMap.forEach((name, ossService) -> finder.put(ossService.channelType() + ":" + ossService.channelName(), ossService));
        }
    }
}
